#include "NPCGroup.h"
#include <cmath>

NPCGroup::NPCGroup()
    : m_pGroupTarget(NULL)
    , m_groupCenter(0, 0, 0)
{
}

NPCGroup::~NPCGroup()
{
    m_members.clear();
}

void NPCGroup::AddNPC(NPC* npc)
{
    if (npc)
    {
        m_members.push_back(npc);
        npc->SetGroup(this);
    }
}

void NPCGroup::RemoveNPC(NPC* npc)
{
    for (auto it = m_members.begin(); it != m_members.end(); ++it)
    {
        if (*it == npc)
        {
            m_members.erase(it);
            break;
        }
    }
}

void NPCGroup::Update(float deltaTime)
{
    if (m_members.empty())
        return;

    // Calculate group center
    m_groupCenter = D3DXVECTOR3(0, 0, 0);
    int aliveCount = 0;

    for (size_t i = 0; i < m_members.size(); i++)
    {
        if (!m_members[i]->IsDead())
        {
            m_groupCenter += m_members[i]->GetPosition();
            aliveCount++;
        }
    }

    if (aliveCount > 0)
    {
        m_groupCenter /= (float)aliveCount;
    }

    // Group decision: if majority is chasing, all should chase
    int chasingCount = 0;
    for (size_t i = 0; i < m_members.size(); i++)
    {
        if (m_members[i]->GetState() == NPC_STATE_CHASE ||
            m_members[i]->GetState() == NPC_STATE_ATTACK)
        {
            chasingCount++;
        }
    }

    // If more than half are engaged, coordinate attack
    if (chasingCount > (int)m_members.size() / 2 && m_pGroupTarget)
    {
        // All NPCs should engage the same target
        for (size_t i = 0; i < m_members.size(); i++)
        {
            if (!m_members[i]->IsDead())
            {
                m_members[i]->SetTarget(m_pGroupTarget);
            }
        }
    }
}

void NPCGroup::SetGroupTarget(GameObject* target)
{
    m_pGroupTarget = target;
}

D3DXVECTOR3 NPCGroup::GetFormationPosition(int index, const D3DXVECTOR3& centerPos)
{
    // Simple circle formation
    int memberCount = GetMemberCount();
    if (memberCount == 0)
        return centerPos;

    float angle = (float)index / memberCount * 2.0f * D3DX_PI;
    float radius = 20.0f;

    return centerPos + D3DXVECTOR3(
        cos(angle) * radius,
        0.0f,
        sin(angle) * radius
    );
}
